
var puts = require('sys').puts, globals = {};
globals.dir = process.argv.pop();


(globals.watcher = function fileWatchingStuff() {
	var watchDir = require('./dir').watchDir, exec = require('child_process').exec,
	statSync = require('fs').statSync, dir = globals.dir;

	function rsync(file) {
		puts(new Date() + ' ' + file); 
		exec('rake rsync', function(err,stdout, stderr) {
			if(globals.client) {
				puts('sending reload cmd to client');
				globals.client.send('reload');
			}
		});
		watchDir(dir, rsync);
	}

	function copyFile(file) {
		puts(new Date() + ' ' + file); 
		var cmd = 'cp -v ' + file + ' ' + file.replace(dir, '/home/xxx/palm/remote-app');
		exec(cmd, function(err, stdout,stderr) {
			puts(cmd);
			if (!err && globals.client) {
				puts('sending reload cmd to client');
				globals.client.send('reload');
			}
		});
		globals.client.send('reload');
		watchDir(dir, rsync);
	}

	//if (statSync(dir).isDirectory()) { watchDir(dir,rsync); }
	if (statSync(dir).isDirectory()) { watchDir(dir,copyFile); }
})();


(function doExpressWebappStuff() {
	var express = require('express'), port = 4567, fs = require('fs');
	var app = express.createServer();
	app.listen(port);
	app.configure(function(){ 
		app.use(express.staticProvider(__dirname + '/public')); 
		app.set('views', __dirname + '/views');
	});


	var json = JSON.parse(fs.readFileSync(globals.dir + '/appinfo.json'));
	puts(JSON.stringify(json));

	puts("Express server listening on port " + port);

	app.get('/', function(req,res) {
		res.render('index.jade', {
			locals: {
				title: 'Express baby',
				app: json
			}
		});
	});

	
	globals.app = app;
})();


(function doWebSocketStuff() {
	var listen = require('socket.io').listen;
	listen(globals.app).on('connection', function(client){ 
		globals.client = client;
		puts('client connected');
		client.on('disconnect', function() { puts('client disconnect'); });
	}); 
})();







